package org.batatasframework.support.database.sql.field;

import org.batatasframework.support.database.DatabaseType;
import org.batatasframework.support.database.metadatas.FieldMetadata;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.database.sql.FieldFragment;
import org.batatasframework.support.database.sql.TableRuntimeMaster;
import org.batatasframework.support.database.sql.TableInstance;

import cn.bonoon.kernel.util.StringHelper;

/**
 * @author jackson
 *
 */
public abstract class AbstractFieldElement extends FieldFragment implements FieldElement{

	/** 在调用的时候才，如果别名为空，则生成一个别名；只允许赋值一次 */
	private String alias;
	
	protected final TableRuntimeMaster master;
	
	public AbstractFieldElement(TableRuntimeMaster master, TableInstance tableSource, FieldMetadata fieldMetadata) {
		super(tableSource, fieldMetadata);
		this.master = master;
	}
	
	public void setAlias(String alias) {
		if(StringHelper.isNotEmpty(this.alias))
			throw new RuntimeException("字段的另外不允许多次定义，否则会出现异常！");
		this.alias = alias;
	}
	
	@Override
	public String getAlias() {
		if(StringHelper.isEmpty(alias)) alias = master.newAliasName();
		return alias;
	}

	@Override
	public String getName() {
		return getAlias();
	}

	@Override
	public int getOrdinal() {
		return fieldMetadata.getOrdinal();
	}

	@Override
	public String getTitle() {
		return fieldMetadata.getTitle();
	}

	@Override
	public DatabaseType getDataType() {
		return fieldMetadata.getDataType();
	}

	@Override
	public Object getFormat() {
		return fieldMetadata.getFormat();
	}

	@Override
	public TableMetadata getTableMetadata() {
		return master;
	}

	@Override
	public boolean enabled() {
		return true;
	}
	@Override
	public String getcolumnName() {
		
		return fieldMetadata.getcolumnName();
	}
}
